package com.jl15988.chainlog.context;

import com.jl15988.chainlog.model.ChainApiLog;
import com.jl15988.chainlog.model.ChainMethodLog;

import java.util.Stack;

/**
 * 监控上下文，用于管理当前线程的监控信息
 */
public class ChainLogContext {

    private static final ThreadLocal<ChainApiLog> CHAIN_API_CONTEXT = new ThreadLocal<>();
    private static final ThreadLocal<Stack<ChainMethodLog>> CHAIN_METHOD_CONTEXT = new ThreadLocal<>();

    /**
     * 设置当前接口监控信息
     */
    public static void setApiMonitorInfo(ChainApiLog chainApiLog) {
        CHAIN_API_CONTEXT.set(chainApiLog);
    }

    /**
     * 获取当前接口监控信息
     */
    public static ChainApiLog getChainApiLog() {
        return CHAIN_API_CONTEXT.get();
    }

    /**
     * 清除接口监控信息
     */
    public static void clearChainApiLog() {
        CHAIN_API_CONTEXT.remove();
    }

    /**
     * 推入链式监控信息
     */
    public static void pushChainMethodLog(ChainMethodLog chainMethodLog) {
        Stack<ChainMethodLog> stack = CHAIN_METHOD_CONTEXT.get();
        if (stack == null) {
            stack = new Stack<>();
            CHAIN_METHOD_CONTEXT.set(stack);
        }
        stack.push(chainMethodLog);
    }

    /**
     * 弹出链式监控信息
     */
    public static ChainMethodLog popChainMethodLog() {
        Stack<ChainMethodLog> stack = CHAIN_METHOD_CONTEXT.get();
        if (stack == null || stack.isEmpty()) {
            return null;
        }
        ChainMethodLog info = stack.pop();
        if (stack.isEmpty()) {
            CHAIN_METHOD_CONTEXT.remove();
        }
        return info;
    }

    /**
     * 获取当前链式监控信息（不弹出）
     */
    public static ChainMethodLog getCurrentChainMethodLog() {
        Stack<ChainMethodLog> stack = CHAIN_METHOD_CONTEXT.get();
        if (stack == null || stack.isEmpty()) {
            return null;
        }
        return stack.peek();
    }

    /**
     * 获取上级链式监控信息
     */
    public static ChainMethodLog getParentChainMethodLog() {
        Stack<ChainMethodLog> stack = CHAIN_METHOD_CONTEXT.get();
        if (stack == null || stack.size() < 2) {
            return null;
        }
        return stack.get(stack.size() - 2);
    }

    /**
     * 获取当前调用层级
     */
    public static int getCurrentLevel() {
        Stack<ChainMethodLog> stack = CHAIN_METHOD_CONTEXT.get();
        return stack == null ? 0 : stack.size();
    }

    /**
     * 清除所有监控上下文
     */
    public static void clearAll() {
        clearChainApiLog();
        CHAIN_METHOD_CONTEXT.remove();
    }
}